<template>
  <div>
    <div class="input">
      <single-image
        v-if="params.inputType === 'single-image'"
        @dataOk="onDataOk"
      ></single-image>
      <double-image
        v-else-if="params.inputType === 'double-image'"
        @dataOk="onDataOk"
      ></double-image>
      <double-image-side
        v-else-if="params.inputType === 'double-image-with-side'"
        @dataOk="onDataOk"
        :input-meta="inputMeta"
      ></double-image-side>
      <text-input
        v-else-if="params.inputType === 'text-input'"
        @dataOk="onDataOk"
      ></text-input>
      <video-input
        v-else-if="params.inputType === 'single-video'"
        @dataOk="onDataOk"
      ></video-input>
      <voice-input
        v-else-if="params.inputType === 'voice-input'"
        @dataOk="onDataOk"
      ></voice-input>
      <video-stream-input
        v-else-if="params.inputType === 'websocket'"
        @dataOk="onDataOk"
        @changeTaskId="changeTaskId"
        :taskId="taskId"
        @changehasResult="changehasResult"
      />
      <charts-input
        ref="chartsInput"
        @dataOk="onDataOk"
        :listId="params.id"
        v-else-if="params.inputType === 'json'"
      />
    </div>
    <van-divider v-if="hasResult"> </van-divider>
    <div v-if="hasResult" class="result-wrapper">
      <div class="result">
        <div>
          <p v-if="params.id==='aiConstruct_12'">
            未来1小时负荷量
          </p>
          <p v-else>处理结果</p>
        </div>
        <div v-if="params.inputType !== 'websocket'">
          <p>网络耗时：{{ totalTime - calcTime }}ms</p>
          <p>计算耗时：{{ calcTime }}ms</p>
        </div>
        <!-- <div v-else>
           <p>当前画面人数：{{result.count}}人</p>
        </div> -->
      </div>
      <div v-if="error" class="error">
        <div>
          <img src="imgs/error.png" />
          <p>无法识别</p>
        </div>
      </div>
      <div v-else-if="noResult" class="error">
        <div>
          <img src="imgs/error.png" />
          <p>无识别结果</p>
        </div>
      </div>
      <div v-else>
        <image-result
          v-if="resultImage"
          :result-img="resultImage"
          :landmarks="landmarks"
          :rects="rects"
          :lines="lines"
        ></image-result>
        <text-result :result-text="simpleTexts"></text-result>
        <table-result :result-list="textList"></table-result>
      </div>
    </div>
    <div class="btn-container">
      <van-button
        v-if="params.inputType !== 'websocket'"
        :disabled="!hasInput"
        type="primary"
        @click="save"
        >{{ btnText }}</van-button
      >
      <van-button v-else :disabled="!hasInput" type="primary" @click="save">{{
        btnText
      }}</van-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { AlgorithmExp } from '@/model/algorithm'
import { apiAxios } from '@/api/axios'
import { algorithms } from '@/store/modules/Algorithm'
import {
  createSocket,
  sendWSPush,
  clearIntervalWesocketPush,
  closeSocket
} from '@/utils/websocket'
import chartsInput from '@/components/input/chartsInput.vue'
@Component
export default class Exp extends Vue {
  private expParam = {};
  get params (): AlgorithmExp {
    return this.expParam as AlgorithmExp
  }

  hasResult = false;
  totalTime = 0;
  error = false;
  noResult = false;
  hasInput = false;
  result: any = {};
  Socket: any = '';

  resultImage = '';
  taskId = '';

  get inputMeta (): string[] | undefined {
    if (this.params.inputMeta && this.params.inputMeta.length > 0) {
      return this.params.inputMeta
    }
  }

  get landmarks (): any[] {
    return this.result.landmarks ? this.result.landmarks : []
  }

  get rects (): any[] {
    return this.result.rects ? this.result.rects : []
  }

  get lines (): any[] {
    return this.result.lines ? this.result.lines : []
  }

  get simpleTexts (): string[] {
    return this.result.simpleTexts ? this.result.simpleTexts : []
  }

  get textList (): any[] {
    return this.result.list ? this.result.list : []
  }

  get calcTime (): number {
    return this.result ? this.result.calcTime : 0
  }

  get btnText (): string {
    return this.calcTime ? '重新计算' : '计算'
  }

  changeTaskId (val: string): void {
    this.taskId = val
  }

  changehasResult (val: any): void {
    this.hasResult = val
    this.result = { count: 0 }
    this.resultImage = ''
  }

  async created () {
    const resp = await apiAxios.get(
      `/open/algorithm/${this.$route.params.id}/exp`
    )
    this.expParam = resp.data
  }

  mounted () {
    this.$store.state.api.images = ['', '']
    this.$store.state.api.videos = ['']
    let algorithmName = ''
    algorithms.list.forEach((group) => {
      group.list.forEach((algorithm) => {
        if (algorithm.id === this.$route.params.id) {
          algorithmName = algorithm.title
        }
      })
    })
    this.$store.state.var.title = algorithmName
    if (algorithmName === '') {
      this.$router.push('/' + algorithms.list[0].list[0].id)
    }
  }

  onDataOk (ok: boolean) {
    this.hasInput = ok
  }

  getsocketData (e: any) {
    // 创建接收消息函数
    const data = e && e.detail.data
    const result = JSON.parse(data)
    this.hasInput = true
    if (result.taskId === this.taskId) {
      this.result = result
      this.resultImage = 'data:image/jpeg;base64,' + this.result.image
    }
  }

  async save ():Promise<void> {
    const startTime = Date.now()
    try {
      this.hasResult = false
      this.result = { count: 0 }
      this.resultImage = ''
      this.error = false
      this.noResult = false
      if (this.params.inputType === 'websocket') {
        let wsBase = '/'
        if (wsBase.startsWith('/')) {
          const wsSchema =
            window.location.protocol === 'https:' ? 'wss:' : 'ws:'
          wsBase = `${wsSchema}//${window.location.host}${wsBase}ai/open`
        }

        if (this.Socket === '') {
          this.Socket = createSocket(
            `${wsBase}/websocket/algorithm/video/call`
          )
        }
        window.addEventListener('onmessageWS', this.getsocketData)
        sendWSPush({
          algoId: this.$route.path.split('/')[2],
          taskId: this.taskId
        })
        this.hasInput = false
      } else {
        let resp: any = null
        if (this.params.inputType === 'json') {
          const data = JSON.parse(
            JSON.stringify((this.$refs.chartsInput as chartsInput).data)
          )
          data.forEach((item: any) => {
            delete item.index
          })
          resp = await apiAxios.post(
            `/open/algorithm/${this.$route.params.id}/call`,
            { content: JSON.stringify(data) }
          )
        } else {
          resp = await apiAxios.post(
            `/open/algorithm/${this.$route.params.id}/call`,
            this.$store.state.api
          )
        }

        this.totalTime = Date.now() - startTime
        this.result = resp.data
        const code = (resp as any).code
        if (code !== 0) {
          this.error = true
        } else {
          if (this.result.noResult) {
            this.noResult = true
          } else if (this.result.image === '__ORIGIN__') {
            this.resultImage =
              'data:image/jpeg;base64,' + this.$store.state.api.images[0]
          } else {
            this.resultImage = this.result.image
          }
        }
      }
    } catch (e) {
      this.error = true
    }
    this.hasResult = true
  }

  beforeDestroy (): void {
    if (this.params.inputType === 'websocket') {
      window.removeEventListener('onmessageWS', this.getsocketData)
      clearIntervalWesocketPush()

      // console.log(123)
    } else {
      if (this.Socket !== '') {
        closeSocket()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-container {
  padding: 1.25rem;
}
.result-wrapper {
  min-height: 21rem;
  padding: 1.25rem;
  .result {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-family: PingFangSC-Regular;
    margin-bottom: 1.25rem;
    & > div:first-child {
      font-size: 1.25rem;
      color: #323333;
    }
    & > div:last-child {
      font-size: 0.88rem;
      color: #929292;
    }
  }
  .secondary {
    font-size: 0.88rem;
    color: #929292;
  }
  .error {
    min-height: 14.8rem;
    display: table;
    margin: 0 auto;

    & > div {
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    img {
      width: 5rem;
      height: 5rem;
    }
    p {
      font-size: 1.25rem;
      color: #323333;
      margin-top: 1.25rem;
    }
  }
}
</style>
